package com.ctshk.common.utils;

import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;

public class UrlToPdfUtil {
    //private static final String OUT_PUT_PDF_PATH = "/home/data/pdf/"; //pdf文件的存放路径（Linux）
    private static final String OUT_PUT_PDF_PATH = "D:/data/pdf/"; //pdf文件的存放路径（windows）

    /**
     * @Title 网页转存为PDF文件
     * @param url 链接地址
     * @param outputFileName 转存的PDF文件名
     */
    public static String urlToPdf(String url, String outputFileName) {
        try {
            String folder = DateUtil.fmtYear(LocalDate.now());
            String outputFile = OUT_PUT_PDF_PATH + folder +"/"+ outputFileName;
            File targetFile = new File(outputFile);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs(); // 创建父级文件路径
            }
            OutputStream os = new FileOutputStream(outputFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            //fontResolver.addFont("/usr/share/fonts/chinese/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //Linux
            fontResolver.addFont("c:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //windows
            renderer.layout();
            renderer.createPDF(os);
            os.close();
            return outputFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
//    public static void main(String[] args) {
//        urlToPdf("http://www.lrfun.com/toPdf.html", "201905098888888.pdf");
//    }
}
